/*
Copyright (C) 2021-2025 Casa Xu (also Zhiyan Xu) from HIT

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

/*
 * LOS_PWM.c
 *
 *  Created on: 2023年2月28日
 *      Author: 64435
 */


#include "LOS_SYS.h"

static const uint32 s_het1pwmPolarity_mod[8U] =
{
    3U,
    3U,
    3U,
    3U,
    3U,
    3U,
    3U,
    3U,
};

/** @fn void LOS_PWM_Init()
*   @brief PWM初始化
*   @note 平平无奇的硬件隔离函数
*/
void LOS_PWM_Init()
{
    hetInit();
}


/** @fn void LOS_PWM_SetSignal(uint32_t LOS_PWMNUM, uint32_t in_duty, double in_period)
*   @brief PWM设置函数
*   @param[in] LOS_PWMNUM PWM号，例如LOS_PWMX1
*   @param[in] in_duty 占空比，百分数%
*   @param[in] in_period 周期，单位us
*   @note 设置PWM的周期和占空比
*/
void LOS_PWM_SetSignal(uint32_t LOS_PWMNUM, uint32_t in_duty, double in_period)
{
    hetSIGNAL_t signal;
    signal.duty = in_duty;
    signal.period = in_period;
    pwmSetSignal_mod(hetRAM1, LOS_PWMNUM, signal);
}

void pwmSetSignal_mod(hetRAMBASE_t * hetRAM, uint32 pwm, hetSIGNAL_t signal)
{
    uint32 action;
    uint32 pwmPolarity = 0U;
    float64 pwmPeriod = 0.0F;

    if(hetRAM == hetRAM1)
    {
        pwmPeriod = (signal.period * 1000.0F) / 853.333F;
        pwmPolarity = s_het1pwmPolarity_mod[pwm];
    }
    else
    {
    }

    action = pwmPolarity;
    

    hetRAM->Instruction[(pwm << 1U) + 41U].Control = ((hetRAM->Instruction[(pwm << 1U) + 41U].Control) & (~(uint32)(0x00000018U))) | (action << 3U);
    hetRAM->Instruction[(pwm << 1U) + 41U].Data = ((((uint32)pwmPeriod * signal.duty) / 100U) << 7U ) + 128U;
    hetRAM->Instruction[(pwm << 1U) + 42U].Data = ((uint32)pwmPeriod << 7U) - 128U;

}
